<template>
  <div class="goods">
    <div class="wrap">
      <Crumb> </Crumb>
      <img src="../assets/img/banner.4c6b6225.png" width="100%" alt="" />
      <ul class="options">
        <li>
          <strong>排序：</strong>
          <span
            :class="num1 == index ? 'active' : ''"
            v-for="(item, index) in options1"
            :key="index"
            @click="didFn(item.min, item.max, index)"
            >{{ item.txt }}</span
          >
        </li>
        <li>
          <strong>分类：</strong>
          <span
            :class="num2 == index ? 'active' : ''"
            v-for="(item, index) in options2"
            :key="index"
            @click="typeFn(item.type, index)"
            >{{ item.txt }}</span
          >
        </li>
      </ul>

      <List :arr="goodsListShow" />
    </div>
    <div style="text-align: center; margin-top: 30px">
      <i :class="isReachBottom?'':'iconfont icon-loading loading'"></i>
      {{ isReachBottom ? "已经到底啦~~~" : "加载中~请稍后~~" }}
    </div>
  </div>
</template>                            
<script>
import Crumb from "../components/Crumb.vue";
import List from "../components/home/List.vue";
import { GoodsSeachAPI } from "@/request/api";
import { getScrollTop, getClientHeight, getScrollHeight } from "@/utils";
export default {
  data() {
    return {
      goodsList: [],
      //显示数组
      goodsListShow: [],
      //栏目
      did: 0,
      //类型
      type: 0,
      //最小值
      min: 0,
      //最大值   当最大值为0的时候默认返回全部
      max: 0,
      //搜索关键词
      keyword: "",
      options1: [
        { min: 0, max: 0, txt: "全部" },
        // "我还可以兑换"的max值是Header组件的coin值
        { min: 0, max: 0, txt: "我还可以兑换" },
        { min: 0, max: 500, txt: "0-500分" },
        { min: 500, max: 1000, txt: "500-1000分" },
        { min: 1000, max: 1500, txt: "1000-1500分" },
        { min: 1500, max: 2500, txt: "1500-2500分" },
        { min: 2500, max: 6500, txt: "2500-6500分" },
        { min: 6500, max: 10000, txt: "6500-10000分" },
      ],
      // 分类数组项
      options2: [
        { type: 0, txt: "全部" },
        { type: 1, txt: "实体商品" },
        { type: 2, txt: "虚拟商品" },
      ],
      // 排序当前项
      num1: 0,
      // 分类当前项
      num2: 0,
      page: 1,
      size: 8,
      isLoading: false,
      isReachBottom: false,
    };
  },
  components: {
    Crumb,
    List,
  },
  created() {
    console.log("goods", this.$route.query.keyword);
    this.keyword = this.$route.query.keyword || "";

    this.goodsSearch();
  },
  mounted() {
    window.addEventListener("scroll", this.scrollFn);
  },
  beforeDestroy() {
    window.removeEventListener("scroll", this.scrollFn);
  },
  /*
   *页码概念？滚动到一定位置时，加载下一页的数据。
打开产品页面时，默认只加载第一页的数据（8条）
正常情况：每次加载下一页数据时，是往后端发起新的请求 请求某一页数据。
积分商城于后面已有odsList给找们,今做一个模拟。
|滚动到一定位置时，往goodsList获取下一页的数据。
1．默认只加载第一页的数据（8条）
2．先绑定滚动事件... onscroll
mounted（）
beforeDestroy（） 
   */
  methods: {
    async goodsSearch() {
      let res = await GoodsSeachAPI({
        did: this.did,
        type: this.type,
        min: this.min,
        max: this.max,
        keyword: this.keyword,
      });
      this.goodsList = res.data;
      //初始化显示第一页的数据
      this.goodsListShow = this.goodsList.filter((item, index) => index < 8);
      //初始化：默认加载第一页
      this.page = 1;
      //初始化：判断是否加载完毕
      this.isReachBottom = false;
       if (this.goodsListShow.length == this.goodsList.length) {
        this.isReachBottom = true;
        return;
      }
      
    },
    didFn(min, max, idx) {
      this.min = min;
      this.max = max;
      this.num1 = idx;
      console.log(min, max);
      this.goodsSearch();
    },
    typeFn(type, idx) {
      this.type = type;
      this.num2 = idx;
      this.goodsSearch();
    },
    scrollFn() {
      console.log("滚了", getScrollTop(), getClientHeight(), getScrollHeight());
      if (getClientHeight() + getScrollTop() >= getScrollHeight() - 270) {
        console.log("可以准备加载了");

        if (this.goodsListShow.length == this.goodsList.length) {
          this.isReachBottom = true;
          return;
        }

        //需求:加载完当前这一页时，再去加载下一页的数据。
        //节流:让一段代码在一段时间之内只执行一次。
        if (this.isLoading == false) {
          this.isLoading = true;
          this.page++; //下一页
          setTimeout(() => {
            for (
              let i = (this.page - 1) * this.size;
              i < this.page * this.size;
              i++
            ) {
              console.log("page:", this.page, "i", i, this.goodsList[i]);
              this.goodsList[i] && this.goodsListShow.push(this.goodsList[i]);
            }
            this.isLoading = false;
          }, 500);
        }
      }
    },
  },
  // watch: {
  //   "$route.query.keyword": {
  //     handler(newVal, oldVal) {
  //       this.keyword = newVal;
  //       this.goodsSearch();
  //     },
  //   },
  // },
  beforeRouteUpdate(to, from, next) {
    //何时触发： 当keyword参数发生变化时触发
    //可以访问组件实力 `this`
    next();
    this.keyword = to.query.keyword;
    //重新请求查询
    this.goodsSearch();
  },
};
</script>
 
<style lang = "less" scoped>
@import "../assets/css/public.less";

.goods {
  padding-bottom: 50px;
  background: #efefef;
  padding-top: 20px;
  .options {
    padding-top: 20px;
    padding-bottom: 40px;
    li {
      margin-top: 20px;
      strong {
        color: #000;
        font-weight: bold;
      }
      span {
        margin-right: 20px;
        margin-left: 10px;
        cursor: pointer;
        color: #999;
        &.active {
          color: @base-color;
          font-weight: bold;
        }
      }
    }
  }
}
.loading {
  display: inline-block;
  animation: loading 2s linear infinite forwards;
}
@keyframes loading {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>